<!--
author:        hejy <silentmanager@163.com>
date:          2024-11-01 00:04:56
component:     index
Copyright © YourCompanyName All rights reserved
酒水上架
-->
<template>
  <div>
    <!-- 表单 -->
    <el-card>
      <FormComponent ref="formRef" :config="formConfig">
        <template #submit>
          <!-- 自定义提交和重置按钮 -->
          <div style="margin-left: 24px">
            <el-button @click="handleQuery">
              <Icon icon="ep:search" class="mr-5px" />
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon icon="ep:refresh" class="mr-5px" />
              重置
            </el-button>
            <el-button
              type="primary"
              plain
              @click="showDialog(MODALTYPE.ADD)"
              v-hasPermi="['bms:drink-inventory:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" />
              新增
            </el-button>
          </div>
        </template>
      </FormComponent>
    </el-card>

    <!-- 表格 -->
    <el-card style="margin-top: 24px">
      <el-table v-loading="loading" :data="list" style="width: 100%">
        <el-table-column label="序号" width="80">
          <template #default="scope">
            {{ scope.$index + 1 + (queryParams.pageNo - 1) * queryParams.pageSize }}
          </template>
        </el-table-column>
        <el-table-column label="酒水编号" prop="drinkCode" />
        <el-table-column label="酒水名称" prop="drinkName" />
        <el-table-column label="价格" prop="price" />
        <el-table-column label="销售额" prop="revenue" />
        <el-table-column label="瓶数" prop="bottleCount" />
        <el-table-column label="包裹数" prop="packageCount" />
        <el-table-column label="库存数量" prop="stock" />
        <el-table-column label="自定义奖金规则" prop="bonusRule" />
        <el-table-column label="是否上架" prop="isListed">
          <template #default="scope">
            <span>{{ scope.row.isListed ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <div style="display: flex">
              <el-button
                v-hasPermi="['bms:drink-inventory:update']"
                link
                type="primary"
                @click="updateStock(scope.row.id)"
                >库存
              </el-button>
              <el-button
                v-hasPermi="['bms:drink-inventory:update']"
                link
                type="primary"
                @click="showDialog(MODALTYPE.EMIT, scope.row.id)"
                >编辑
              </el-button>
              <el-button
                v-hasPermi="['bms:drink-inventory:query']"
                @click="showDialog(MODALTYPE.DETAIL, scope.row.id)"
                link
                type="primary"
                >详情
              </el-button>
              <el-button
                v-hasPermi="['bms:drink-inventory:delete']"
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                >删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 操作弹窗 -->
    <Operation
      :id="modalId"
      v-model:visible="isDialogVisible"
      :modalType="modalType"
      @refresh-table="getList"
    />
    <!-- 库存更新对话框 -->
    <el-dialog v-model="dialogVisible" title="更新库存" width="400px" append-to-body>
      <el-form :model="form" ref="formRef" label-width="100px">
        <el-form-item label="库存增加数量">
          <el-input-number v-model="form.quantityChange" :min="-999" :max="999" label="数量" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateStock">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import Operation from './components/operation.vue'
import { MODALTYPE } from '@/types/ref'
import {
  deleteDrinkInventory,
  DrinkInventoryUpdateRequest,
  DrinkItem,
  pageDrinkInventory, updateStockApi
} from '@/api/drinks/drinks-put'
import FormComponent from '@/components/FormComponent/index.vue'
import { defaultTime } from '@/utils'

const message = useMessage() // 消息弹窗

// ----------------------------- 操作弹窗状态 -----------------------------
const isDialogVisible = ref<boolean>(false) // 定义对话框可见性的状态
// 显示弹窗的处理函数
const modalType = ref<MODALTYPE>(MODALTYPE.ADD)
const modalId = ref<string>('')
const showDialog = (type: MODALTYPE, id?: string) => {
  isDialogVisible.value = true // 显示弹窗
  modalId.value = id || ''
  modalType.value = type
}

// ----------------------------- 更新库存弹窗状态 -----------------------------
const dialogVisible = ref<boolean>(false) // 定义对话框可见性的状态

const form = reactive<DrinkInventoryUpdateRequest>({
  drinkId: '',
  quantityChange: 0
})
const updateStock = (id?: string) => {
  form.drinkId = id || ''
  form.quantityChange = 0
  dialogVisible.value = true // 显示弹窗
}
const handleUpdateStock = () => {
  const { quantityChange } = form
  if (quantityChange === 0) {
    ElMessage.warning('请输入有效的库存增加数量')
    return
  }
  updateStockApi(form).then(() => {
    ElMessage.success('更新成功')
    dialogVisible.value = false
    getList()
  })
}

// --------------------  表格  ---------------------
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref<DrinkItem[]>([]) // 列表的数据
// 分页
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await pageDrinkInventory({
      ...queryParams,
      ...formRef.value?.formData
    })
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  formRef.value?.handleReset()
  handleQuery()
}
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteDrinkInventory(id)
    message.success('删除成功')
    // 刷新列表
    await getList()
  } catch (e) {
    console.error(e)
  }
}
/** 初始化 */
onMounted(() => {
  getList()
})

// ==================== 表单  ====================
const formRef = ref<InstanceType<typeof FormComponent>>()
const formConfig = [
  {
    label: '酒水编号',
    prop: 'drinkCode',
    type: 'input',
    options: { placeholder: '请输入酒水编号' }
  },
  {
    label: '酒水名称',
    prop: 'drinkName',
    type: 'input',
    options: { placeholder: '请输入酒水名称' }
  },
  {
    label: '价格',
    prop: 'price',
    type: 'number',
    options: { placeholder: '请输入价格', style: { width: '200px' } }
  },
  {
    label: '瓶数',
    prop: 'bottleCount',
    type: 'number',
    options: { placeholder: '请输入瓶数', style: { width: '200px' } }
  },
  {
    label: '包裹数',
    prop: 'packageCount',
    type: 'number',
    options: { placeholder: '请输入包裹数', style: { width: '200px' } }
  },
  {
    label: '自定义奖金规则',
    prop: 'bonusRule',
    type: 'bonusRule',
    options: { placeholder: '请输入自定义奖金规则' },
    itemProps: {
      labelWidth: '110px'
    }
  },
  {
    label: '是否上架',
    prop: 'isListed',
    type: 'radio',
    options: {
      options: [
        { label: '是', value: '1' },
        { label: '否', value: '0' }
      ]
    }
  },
  {
    label: '创建时间',
    prop: 'createTime',
    type: 'date',
    options: {
      type: 'datetimerange',
      defaultTime: defaultTime,
      rangeSeparator: '-',
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间',
      valueFormat: 'YYYY-MM-DD HH:mm:ss'
    }
  }
]
</script>
